﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Security.Claims;
using IdentityRole = Volo.Abp.Identity.IdentityRole;
using IdentityUser = Volo.Abp.Identity.IdentityUser;

namespace EcoSystem
{
    /// <summary>
    ///  替换默认AbpUserClaimsPrincipalFactory处理逻辑
    /// </summary>
    [Dependency(ReplaceServices = true)]
    [ExposeServices(typeof(IUserClaimsPrincipalFactory<IdentityUser>))]
    public class MyUserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory, ITransientDependency
    {
        public MyUserClaimsPrincipalFactory(UserManager<IdentityUser> userManager,
            RoleManager<IdentityRole> roleManager,
            IOptions<IdentityOptions> options,
            ICurrentPrincipalAccessor currentPrincipalAccessor,
            IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory) :
            base(userManager, roleManager, options, currentPrincipalAccessor, abpClaimsPrincipalFactory)
        {

        }

        /// <summary>
        /// 自定义返回claims
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public override async Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
        {
            var principal = await base.CreateAsync(user);
            var identityPrincipal = principal.Identities.First();

            // 添加自定义claim
            identityPrincipal.AddClaim(new Claim(ExtraClaimNames.AccountType, user.GetProperty(nameof(SystemUser.AccountType), 1).ToString()));
            identityPrincipal.AddClaim(new Claim(ExtraClaimNames.RegionCode, user.GetProperty(nameof(SystemUser.RegionCode), "")));
            identityPrincipal.AddClaim(new Claim(ExtraClaimNames.OrganizeId, user.GetProperty(nameof(SystemUser.OrganizeId), "")));
            identityPrincipal.AddClaim(new Claim(ExtraClaimNames.OrganizeCode, user.GetProperty(nameof(SystemUser.OrganizeCode), "")));
            identityPrincipal.AddClaim(new Claim(ExtraClaimNames.EnterpriseId, (user.GetProperty(nameof(SystemUser.EnterpriseId)) ?? "").ToString()));
            return principal;
        }
    }
}